package com.hemaapp.yjnh.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.android.uu.view.ActionSheetDialog;
import com.android.uu.view.ActionSheetDialog.OnSheetItemClickListener;
import com.android.uu.view.ActionSheetDialog.SheetItemColor;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.AddImageAdapter;
import com.hemaapp.yjnh.bean.AfterSale;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.Order.BillChild;
import com.hemaapp.yjnh.bean.ReturnType;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.ImageGridView;
import com.hemaapp.yjnh.view.WheelSelectorDialog;
import com.hemaapp.yjnh.view.YjnhImageWay;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomImageUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 申请售后
 *
 * @author GuiyouZhang
 */
public class ApplyAfterSalesActivity extends BaseActivity implements OnClickListener {

    private final static int PERMISSION_CAMERA = 0x101;
    private final static int PERMISSION_ALBUM = 0x102;

    private final static int REQUEST_CAMERA = 0x01;
    private final static int REQUEST_ALBUM = 0x02;

    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_reason)
    TextView tvReason;
    @Bind(R.id.iv_arrow)
    ImageView ivArrow;
    @Bind(R.id.layout_reason)
    LinearLayout layoutReason;
    @Bind(R.id.tv_total)
    TextView tvTotal;
    @Bind(R.id.edt_description)
    EditText edtDescription;
    @Bind(R.id.image_grid)
    ImageGridView imageGrid;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.layout_cannot)
    LinearLayout layoutCannot;

    private AfterSale afterSale;
    private BillChild goods;
    private YjnhImageWay imageWay;
    private Integer orderby = 0;//上传图片的排序
    private String reason;//退货类型
    private ArrayList<String> types = new ArrayList<>();
    private User user;
    private String recvdate;//收货时间
    private int type = 0;//类型：1新申请的售后，2修改以前的售后
    private AddImageAdapter mImgAdapter;
    private ArrayList<ImgItemsBean> mImages = new ArrayList<>();//图片
    private ArrayList<String> compressPaths;//压缩图片的路径，用于最后删除

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_apply_aftersales);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        getReturnType();
        imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA) {
            @Override
            public void album() {
                // 注意：若不重写该方法则使用系统相册选取(对应的onActivityResult中的处理方法也应不同)
                Intent it = new Intent(mContext, AlbumActivity.class);
                int size = mImages.size();
                it.putExtra("limitCount", 4 - size);// 图片选择张数限制
                it.putExtra("model", 1);// 图片是单选还是多选
                startActivityForResult(it, albumRequestCode);
            }
        };
        refreshImages();
    }

    @Override
    protected void onDestroy() {
        //删除在上传本地图片过程中生成的临时压缩图片
        if (compressPaths != null)
            for (String path : compressPaths) {
                File file = new File(path);
                file.delete();
            }
        super.onDestroy();
    }

    @Override
    protected void getExras() {
        goods = (BillChild) mIntent.getSerializableExtra("goods");
        recvdate = mIntent.getStringExtra("recvdate");
        afterSale = (AfterSale) mIntent.getSerializableExtra("afterSale");
        type = mIntent.getIntExtra("type", 1);
        if ((type == 1 && (goods == null))
                || (type == 2 && afterSale == null)) {
            XtomToastUtil.showShortToast(mContext, "获取商品信息失败");
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    finish();
                }
            }, 1500);
        }
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void setListener() {
        titleText.setText("申请售后");
        titleRightBtn.setText("提交");
        if (checkAvailable()) {
            layoutCannot.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
        } else {
            layoutCannot.setVisibility(View.VISIBLE);
            scrollView.setVisibility(View.GONE);
            titleRightBtn.setVisibility(View.GONE);
        }
        setData();
    }

    private boolean checkAvailable() {
        if (isNull(recvdate)) {//如果还没收货，也可以
            return true;
        }
        boolean result = false;
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d1 = df.parse(recvdate);
            Date now = new Date();
            long diff = now.getTime() - d1.getTime();
            long days = diff / (1000 * 60 * 60 * 24);
            if (days <= 7) {
                result = true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void getReturnType() {
        if (user != null) {
            getNetWorker().returnTypeList(user.getToken());
        }
    }
    /**
     * 当修改售后申请时，将之前填写的数据填充到界面中
     */
    private void setData() {
        if (afterSale != null) {
            reason = afterSale.getReason();
            tvReason.setText(reason);
        }
        tvTotal.setText("¥" + uuUtils.formatAfterDot2(getTotalFee()+""));
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case RETURNTYPE_LIST:
            case ORDER_SAVEOPERATE:
            case FILE_UPLOAD:
                showProgressDialog("请稍候");
                break;
            default:
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case RETURNTYPE_LIST:
            case ORDER_SAVEOPERATE:
            case FILE_UPLOAD:
                cancelProgressDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case RETURNTYPE_LIST:
                HemaPageArrayResult<ReturnType> rResult = (HemaPageArrayResult<ReturnType>) baseResult;
                if (rResult == null || rResult.getObjects() == null)
                    return;
                ArrayList<ReturnType> type1 = new ArrayList<>();
                type1.addAll(rResult.getObjects());
                for (ReturnType type : type1) {
                    this.types.add(type.getname());
                }
                break;
            case ORDER_SAVEOPERATE:
                if (mImages.size() > 0) {
                    upImages();
                } else {
                    showTextDialog("申请成功");
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_ORDER);
                    EventBus.getDefault().post(msg);
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 2000);
                }
                break;
            case FILE_UPLOAD:
                if (mImages.size() > 0) {
                    mImages.remove(0);
                    upImages();
                } else {
                    showTextDialog("申请成功");
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_ORDER);
                    EventBus.getDefault().post(msg);
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 2000);
                }
                break;
            default:
                break;
        }

    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
            case FILE_UPLOAD:
                showTextDialog(baseResult.getMsg());
                break;
            case RETURNTYPE_LIST:
                showTextDialog("数据异常，请稍后再试");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case RETURNTYPE_LIST:
                showTextDialog("数据异常，请稍后再试");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
                break;
            case ORDER_SAVEOPERATE:
                showTextDialog("申请失败");
                break;
            case FILE_UPLOAD:
                showTextDialog("申请失败！");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        setResult(RESULT_OK);
                        finish();
                    }
                }, 2000);
                break;
            default:
                break;
        }
    }

    private String getTotalFee() {
        int count = 1;
        double price = 0.0;
        double freight = 0.0;
        if (afterSale != null) {
            count = Integer.parseInt(afterSale.getBuycount());
            price = Double.valueOf(afterSale.getPrice());
            freight = Double.valueOf(afterSale.getShipping_fee());
        } else {
            count = Integer.parseInt(goods.getBuycount());
            price = Double.valueOf(goods.getPrice());
            freight = Double.valueOf(goods.getShipping_fee());
        }
        return count * price + freight+"";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ALBUM:// 相册选择图片
                album(data);
                break;
            case REQUEST_CAMERA:// 拍照
                camera();
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void camera() {
        String imagepath = imageWay.getCameraImage();
        new CompressPicTask().execute(imagepath);
    }

    // 自定义相册选择时处理方法
    private void album(Intent data) {
        if (data == null)
            return;
        ArrayList<String> imgList = data.getStringArrayListExtra("images");
        if (imgList == null)
            return;
        for (String img : imgList) {
            new CompressPicTask().execute(img);
        }
    }

    private void upImages() {
        if (mImages.size() > 0) {
            String imagePath = mImages.get(0).getImgurl();
            getNetWorker().fileUpload(user.getToken(), "17", goods.getId(),
                    "0", orderby + "", "无", imagePath);
            orderby++;
        }else {
            showTextDialog("申请成功");
            EventBusMsg msg = new EventBusMsg();
            msg.setType(EventBusConfig.UPDATE_ORDER);
            EventBus.getDefault().post(msg);
            titleText.postDelayed(new Runnable() {

                @Override
                public void run() {
                    setResult(RESULT_OK);
                    finish();
                }
            }, 2000);
        }
    }

    /**
     * 显示退货的原因类型
     */
    public void showReasonType() {
        if (types.size() == 0) {
            XtomToastUtil.showShortToast(mContext, "暂无原因，请手动填写");
            return;
        }
        WheelSelectorDialog wheelDialog = new WheelSelectorDialog(mContext).builder();
        wheelDialog.setListener(new WheelSelectorDialog.onSelectedItemListener() {
            @Override
            public void onSelected(int index) {
                reason = types.get(index);
                tvReason.setText(reason);
                ivArrow.setImageResource(R.drawable.arrow_down_grey);
            }
        });
        wheelDialog.setDatas(types);
        wheelDialog.show();
    }

    @OnClick({R.id.title_left_btn, R.id.layout_reason, R.id.title_right_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.layout_reason:
                showReasonType();
                break;
            case R.id.title_right_btn:
                if (types.size() > 0 && isNull(reason)) {
                    XtomToastUtil.showShortToast(mContext, "请选择退货原因");
                    return;
                }
                String content = edtDescription.getText().toString().trim();
//                if (isNull(content)) {
//                    XtomToastUtil.showShortToast(mContext, "请填写退货理由");
//                    return;
//                }
                if (user != null) {
                    if (afterSale != null) {
                        getNetWorker().orderSaveoperate(user.getToken(), afterSale.getId(), "9",
                                reason, content, "自己联系", "000000000");
                    } else {
                        getNetWorker().orderSaveoperate(user.getToken(), goods.getId(), "3",
                                reason, content, "自己联系", "000000000");
                    }
                }
                break;
        }
    }

    /**
     * 刷新图片
     */
    private void refreshImages() {
        if (mImgAdapter == null) {
            mImgAdapter = new AddImageAdapter(mContext, mImages);
            mImgAdapter.setShowDelete(false);
            imageGrid.setAdapter(mImgAdapter);
            mImgAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                    if (mImages.size() < 5 && position == mImages.size()) {
                        showPic();
                    }else if (position < mImages.size()){
                        showImageOpe(position, mImages, mImgAdapter);
                    }
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    mImages.remove(position);
                    mImgAdapter.notifyDataSetChanged();
                }
            });
        } else {
            mImgAdapter.notifyDataSetChanged();
        }
    }

    private void showImageOpe(final int position, final ArrayList<ImgItemsBean> images, final AddImageAdapter adapter) {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("查看大图", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                ArrayList<Img> imgs = new ArrayList<Img>();
                                for (int i = 0; i < images.size(); i++) {
                                    ImgItemsBean item = images.get(i);
                                    String imgurl_detail = item.getImgurlbig();
                                    Img img = new Img(imgurl_detail);
                                    imgs.add(img);
                                }

                                Intent intent = new Intent();
                                intent.setClass(mContext, ShowLargeImageActivity.class);
                                intent.putExtra("imgs", imgs);
                                intent.putExtra("position", position + 1);
                                mContext.startActivity(intent);
                            }
                        })
                .addSheetItem("删除", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                ImgItemsBean imageItem = images.get(position);
                                images.remove(position);
                                adapter.notifyDataSetChanged();
                            }
                        })
                .show();
    }

    /**
     * 显示图片选择对话
     */
    public void showPic() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("相机", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if(ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA)
                                        != PackageManager.PERMISSION_GRANTED) {
                                    ActivityCompat.requestPermissions(mContext,
                                            new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMERA);
                                }else {
                                    if (mImages.size() < 4)
                                        imageWay.camera();
                                    else
                                        XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                                }
                            }
                        })
                .addSheetItem("从相册打开", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if ( mImages.size() < 4)
                                    imageWay.album();
                                else
                                    XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                            }
                        })
                .show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imageWay.camera();
            } else {
                XtomToastUtil.showShortToast(mContext, "请打开相机权限");
            }
        }
    }

    /**
     * 压缩图片
     */
    private class CompressPicTask extends AsyncTask<String, Void, Integer> {
        String compressPath;

        @Override
        protected Integer doInBackground(String... params) {
            try {
                String path = params[0];
                String savedir = XtomFileUtil.getTempFileDir(mContext);
                compressPath = XtomImageUtil.compressPictureWithSaveDir(path,
                        BaseConfig.IMAGE_HEIGHT, BaseConfig.IMAGE_WIDTH,
                        BaseConfig.IMAGE_QUALITY, savedir, mContext);
                return 0;
            } catch (Exception e) {
                return 1;
            }
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在压缩图片");
        }

        @Override
        protected void onPostExecute(Integer result) {
            cancelProgressDialog();
            switch (result) {
                case 0:
                    if (compressPaths == null)
                        compressPaths = new ArrayList<>();
                    compressPaths.add(compressPath);
                    ImgItemsBean imageitem = new ImgItemsBean();
                    imageitem.setImgurl(compressPath);
                    imageitem.setImgurlbig(compressPath);
                    mImages.add(imageitem);
                    refreshImages();
                    break;
                case 1:
                    showTextDialog("图片压缩失败");
                    break;
            }
        }
    }
}
